package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送验证码
     * @param phone
     * @return
     */
    @Override
    public Result sendCode(String phone) {
        //1.验证手机号是否有效
        boolean phoneInvalid = RegexUtils.isPhoneInvalid(phone);
        if (phoneInvalid) {
            return Result.fail("手机号格式错误！");
        }
        //2.生成验证码
        String code = RandomUtil.randomNumbers(6);

        //3.存放临时验证码到redis  设置有效期两分钟
        redisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY +phone,code,RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);

        //4.发送验证码
        //TODO:需调用第三方API 如阿里云
        log.info("验证码：{}",code);

        return Result.ok();



    }

    @Override
    public Result login(LoginFormDTO loginForm) {
        //判断电话号码是否为空
        String phone = loginForm.getPhone();
        if(phone ==null || loginForm.getCode() == null){
            //为空返回错误信息
            return Result.fail("手机号或验证码为空！");
        }

        //判断验证码是否存在、正确

        //校验验证码
        String cacheCode = (String) redisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + loginForm.getPhone());

        if (cacheCode == null || !loginForm.getCode().equals(cacheCode)) {
            return Result.fail("验证码错误！");
        }

        //判断是否新用户
        // 根据手机号查询用户
        User user = query().eq("phone", phone).one();

        if(user == null){
            //添加新用户
            user =insertWithPhone(phone);
        }

        //生成token
        String token = UUID.randomUUID().toString(true);
        //实体类转map
        UserDTO userDTO = new UserDTO();
        BeanUtil.copyProperties(user,userDTO);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO);

        //在redis中存放token--内含用户信息
        String tokenKey = RedisConstants.LOGIN_USER_KEY+token;
        redisTemplate.opsForHash().putAll(tokenKey,userMap);
        //设置有效期
        redisTemplate.expire(tokenKey,RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        //返回token
        return Result.ok(token);





    }

    private User insertWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(SystemConstants.USER_NICK_NAME_PREFIX+RandomUtil.randomNumbers(11));
        save(user);
        return user;
    }


}
